package win.larryzeal.jms.topic.consumer;

import org.apache.activemq.ActiveMQConnectionFactory;
import win.larryzeal.jms.common.Common;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.jms.Topic;

/**
 * Created by 张少昆 on 2017/8/4 0004.
 */
public class MyJmsTopicConsumer {
	public static void main(String[] args){
		//1, connectionFactory
		ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(Common.url);
		//2, create connection
		Connection connection = null;
		Session session = null;
		try{
			connection = connectionFactory.createConnection();
			//3, start the connection
			connection.start();

			boolean transactioned = false;
			//4, start a session
			session = connection.createSession(transactioned, Session.AUTO_ACKNOWLEDGE);//不开启事务；自动应答机制

			//5, set the destination
			Topic topic = session.createTopic(Common.topicName);//NOTE Topic extends Destination

			//6, create consumer
			MessageConsumer consumer = session.createConsumer(topic);

			//7, async consume: register listener
			/*consumer.setMessageListener(new MessageListener() {
				@Override
				public void onMessage(Message message){
					TextMessage msg = (TextMessage) message;
					try{
						System.out.println("收到消息：" + msg.getText());
					} catch(JMSException e){
						e.printStackTrace();
					}
				}
			});*/

			//7, sync consume: receive
			while(true){
				TextMessage msg = (TextMessage) consumer.receive(1000);
				if(msg != null)
					System.out.println("收到消息：" + msg.getText());
				else
					System.out.println("暂无消息");
			}

		} catch(JMSException e){
			e.printStackTrace();
		} /*finally{
			try{
				if(session != null)
					session.close();
//				if(connection != null)
				connection.close();
			} catch(JMSException e){
				e.printStackTrace();
			}
		}*/
	}
}
